from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional
import uvicorn


app = FastAPI()

# Enable CORS for local development
app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:3000", "http://127.0.0.1:3000", "http://localhost:3001", "http://127.0.0.1:3001"],
    # Allow any localhost/127.0.0.1 port
    allow_origin_regex=r"^https?://(localhost|127\.0\.0\.1)(:\\d+)?$",
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

class User(BaseModel):
    id:int
    name:str

fake_users= [
    {"id":1,"name":"Alice"},
    {"id":2,"name":"Bob"}
]

class Task(BaseModel):
    id: Optional[int] = None
    title: str
    assignedId: Optional[int] = None

fake_tasks=[
    {"id":1,"title":"Review documents","assignedId":1},
    {"id":2,"title":"Complete project report","assignedId":2}
]

task_id_counter=2

@app.get("/users")
def get_users():
    return fake_users

@app.get("/tasks")
def get_tasks():
    return fake_tasks

@app.post("/tasks")
def create_task(task:Task):
    try:
        global task_id_counter
        new_task = {"id":task_id_counter,"title":task.title,"assignedId":task.assignedId}
        fake_tasks.append(new_task)
        task_id_counter+=1
        return new_task
    except Exception as e:
        print('get error:',task)
        return {}


if __name__=="__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)